#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>

void printAddrInfo(struct sockaddr_in* addr) {
        char ip[16];
        uint16_t port = ntohs(addr->sin_port);
        if(inet_ntop(AF_INET, &addr->sin_addr, ip, 16) == 0) {
                printf("ntop error.errno=%d errmsg=%s\n", errno, strerror(errno));
                return;
        }
        printf("sock info:[%s:%u]\n", ip, port);
}

void printSockInfo(int fd) {
        struct sockaddr_in addr;
        socklen_t len = sizeof(addr);
        if(getsockname(fd, (struct sockaddr *)&addr, &len) != 0) {
                printf("getsockename error.errno=%d errmsg=%s\n", errno, strerror(errno));
                return;
        }
        printAddrInfo(&addr);
}


int main(int argc, char** argv) {
	if(argc != 3) {
		printf("usage: %s ip port\n", argv[0]);
		return -1;
	}
	uint16_t port = atoi(argv[2]);
	int fd = socket(AF_INET, SOCK_STREAM,0);
	struct sockaddr_in serv_addr;
	struct sockaddr_in client_addr;
	memset(&serv_addr, 0, sizeof(struct sockaddr_in));
	memset(&client_addr, 0, sizeof(struct sockaddr_in));

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(port);
	if(inet_pton(AF_INET, argv[1],&serv_addr.sin_addr) <= 0) {
		printf("parse ip error. errno=%d errmsg=%s\n", errno, strerror(errno));
		return errno;
	}

	client_addr.sin_family = AF_INET;
	client_addr.sin_port = htons(65530);
	if(inet_pton(AF_INET, "192.168.56.1",&client_addr.sin_addr) <= 0) {
		printf("parse ip error. errno=%d errmsg=%s\n", errno, strerror(errno));
		return errno;
	}

	if(bind(fd,(struct sockaddr*)&client_addr, sizeof(client_addr)) != 0) {
		printf("bind error. errno=%d errmsg=%s\n", errno, strerror(errno));
		return errno;
	}
	printSockInfo(fd);
	printAddrInfo(&serv_addr);
	if(connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) != 0) {
		printf("connect error. errno=%d errmsg=%s\n", errno, strerror(errno));
		return errno;
	}

	char recvline[1024];
	int n = 0;
	while((n = read(fd, recvline, 1024)) > 0) {
		recvline[n] = 0;
		printf("%s", recvline);
	}
	// sleep(100);
	close(fd);

	return 0;
}
